import Vue from 'vue'
import Vuex from 'vuex'
const persistPlugin = store => {
	// 读取状态
	let state = uni.getStorageSync('state')
	if (state) {
		store.replaceState(state)
	}
	// 监听状态变化
	store.subscribe((mutation, state) => {
		uni.setStorageSync('state', state)
	})
}

Vue.use(Vuex)
export default new Vuex.Store({
	plugins: [persistPlugin],
	state: {
		token: '',
		userInfo: {},
		cartlist: [],
		code: ''
	},
	mutations: {
		setToken(state, token) {
			state.token = token
		},
		setUserInfo(state, userInfo) {
			state.userInfo = userInfo
		},
		// 清除所有状态
		clearAll(state) {
			state.token = ''
			state.userInfo = {}
		}
	},
	actions: {
		// 获取新的 token
		getNewToken({
			commit
		}) {
			// 这里写自己的后端请求用户刷新 token 的接口
		}
	},
})